package cn.codeforfun.callback;

import cn.codeforfun.callback.handler.SubscribeHandler;
import cn.codeforfun.common.WechatService;
import cn.codeforfun.interceptor.CallbackInterceptor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by Administrator on 2017/2/14 0014.
 */
@Controller
@RequestMapping("/callback")
public class CallBackController {
    @Autowired
    private WechatService wechatService;
    @Autowired
    private SubscribeHandler subscribeHandler;

    @RequestMapping
    @ResponseBody
    @CallbackInterceptor
    public String callback(HttpServletRequest request) {
        String inputStr = (String) request.getAttribute("inXml");//解密之后的字符串
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(inputStr);
        WxMpMessageRouter router = new WxMpMessageRouter(wechatService.getService());
        router
                .rule().msgType(WxConsts.XML_MSG_EVENT).event(WxConsts.EVT_SUBSCRIBE).handler(subscribeHandler).end()
        ;

        // 4个条件必须全部匹配的路由规则
//                .rule().msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_SUBSCRIBE).eventKey("EVENT_KEY").content("CONTENT").rContent("content正则表达式").handler(handler).end()
        // 只匹配1个条件的路由规则
//                .rule().msgType("MSG_TYPE").handler(handler).end()
        // 消息经过这个规则后可以继续尝试后面的路由规则
//                .rule().msgType("MSG_TYPE").handler(handler).next()
        // 另一个同步处理的路由规则
//                .rule().async(false).msgType("MSG_TYPE").handler(handler).end()
        // 添加了拦截器的路由规则
//                .rule().msgType("MSG_TYPE").interceptor(interceptor).handler(handler).end()
        // 兜底路由规则，一般放到最后
//                .rule().handler(handler).end()

// 将WxXmlMessage交给消息路由器
        router.route(inMessage);
        return "";
    }
}
